<?php
/**
* 随机生成一个验证码的内容的函数
* @param $m : 验证码的个数
* @param $type ： 验证码类型， 0: 纯数字  1: 数字 + 小写字母   2 : 数字+大小写字符
 **/
function getCode($m = 4, $type = 2)
{
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $t = array(9, 35, strlen($str) - 1);

    //生成随机验证码所需的内容
    $c = '';
    for ($i = 0; $i < $m; $i++)
    {
        $c .= $str[mt_rand(0, $t[$type])];
    }
    return $c;
}
$str = getCode();
$num = 4;
$width = $num * 20;
$height = 30;
$img = imagecreatetruecolor($width, $height);
$bg = imagecolorallocate($img, 200, 200, 200);
imagefill($img, 0, 0, $bg);
$c = imagecolorallocate($img, 111, 0, 55);
$black = imagecolorallocate($img, 0, 0, 0);

//绘制验证码内容
for ($i = 0; $i < $num; $i++)
{
    imagettftext($img, 18, mt_rand(-40, 40), 8+(18*$i), 24, $c, 'msyh.ttf', $str[$i]);
}
//添加干扰点
for ($i = 0; $i < 200; $i++)
{
    $c = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), $c);
}
//添加干扰线
for ($i = 0; $i < 5; $i++)
{
    $c = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
    imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $c);
}
//添加边框
imagerectangle($img, 0, 0, $width-1, $height-1, $black);
header('Content-Type:image/png');   //header前面不要有任何输出
imagepng($img);
imagedestroy($img);
/**
 * <img src="code.php" onclick="this.src='code.php?id='+Math.random()">
 **/
?>
